<template>
  <div class="withdraw-audit">
    <el-card>
      <div slot="header" class="clearfix">
        <span class="page-title"><i class="el-icon-money"></i> 提现审核管理</span>
        <div class="header-actions">
          <el-button
            v-if="!isHeadquarters"
            class="add-btn"
            type="primary"
            icon="el-icon-plus"
            @click="showAddDialog">
            <span class="btn-text">添加提现申请</span>
          </el-button>
        </div>
      </div>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="审核状态">
            <el-select v-model="searchForm.statue" placeholder="请选择状态" clearable>
              <el-option label="待审核" :value="1"></el-option>
              <el-option label="已通过" :value="2"></el-option>
              <el-option label="已拒绝" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              placeholder="选择开始时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              placeholder="选择结束时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <configurable-table
        :columns="tableColumns"
        :data="tableData"
        :loading="loading"
        :show-pagination="true"
        :current-page.sync="pagination.current"
        :page-size.sync="pagination.size"
        :pagination-total="pagination.total"
        @page-change="loadData"
        border>
        <!-- 用户类型列 -->
        <template #userType="{ row }">
          <el-tag :type="getUserTypeTag(row.userType)">
            {{ getUserTypeText(row.userType) }}
          </el-tag>
        </template>
        <!-- 提现金额列 -->
        <template #amount="{ row }">
          ¥{{ (row.amount / 100).toFixed(2) }}
        </template>
        <!-- 审核状态列 -->
        <template #statue="{ row }">
          <el-tag :type="getStatusTag(row.statue)">
            {{ getStatusText(row.statue) }}
          </el-tag>
        </template>
        <!-- 操作列 -->
        <template #actions="{ row }">
          <el-button size="mini" icon="el-icon-view" @click="handleView(row)">查看</el-button>
          <el-button
            v-if="row.statue === 1"
            size="mini"
            type="success"
            icon="el-icon-check"
            @click="handleApprove(row)">
            通过
          </el-button>
          <el-button
            v-if="row.statue === 1"
            size="mini"
            type="danger"
            icon="el-icon-close"
            @click="handleReject(row)">
            拒绝
          </el-button>
          <el-button
            v-if="row.statue === 3"
            size="mini"
            type="warning"
            icon="el-icon-edit"
            @click="handleEdit(row)">
            {{ row.statue === 3 ? '重新提交' : '编辑' }}
          </el-button>
        </template>
      </configurable-table>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog title="提现详情" :visible.sync="detailDialogVisible" width="600px" custom-class="view-dialog">
      <div class="detail-content" v-if="detailData">
        <div class="detail-item">
          <label>提现ID：</label>
          <span>{{ detailData.id || '无' }}</span>
        </div>
        <div class="detail-item">
          <label>用户ID：</label>
          <span>{{ detailData.userId || '无' }}</span>
        </div>
        <div class="detail-item">
          <label>用户类型：</label>
          <span>{{ getUserTypeText(detailData.userType) }}</span>
        </div>
        <div class="detail-item">
          <label>提现金额：</label>
          <span>¥{{ detailData.amount ? (detailData.amount / 100).toFixed(2) : '0.00' }}</span>
        </div>
        <div class="detail-item">
          <label>审核状态：</label>
          <el-tag :type="getStatusTag(detailData.statue)">
            {{ getStatusText(detailData.statue) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <label>拒绝原因：</label>
          <span>{{ detailData.reason || '无' }}</span>
        </div>
        <div class="detail-item">
          <label>申请时间：</label>
          <span>{{ detailData.createTime || '无' }}</span>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加提现申请对话框 -->
    <el-dialog title="添加提现申请" :visible.sync="addDialogVisible" width="500px" :close-on-click-modal="false" custom-class="action-dialog">
      <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="120px">
        <el-form-item label="用户ID" prop="userId">
          <el-input-number v-model="addForm.userId" :min="1" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="addForm.userType" placeholder="请选择用户类型" style="width: 100%">
            <el-option label="C端用户" :value="1"></el-option>
            <el-option label="业务员" :value="2"></el-option>
            <el-option label="商家" :value="3"></el-option>
            <el-option label="区域代理" :value="4"></el-option>
            <el-option label="总公司" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提现金额(分)" prop="amount">
          <el-input-number v-model="addForm.amount" :min="1" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="审核状态" prop="statue">
          <el-select v-model="addForm.statue" placeholder="请选择审核状态" style="width: 100%">
            <el-option label="待审核" :value="1"></el-option>
            <el-option label="已通过" :value="2"></el-option>
            <el-option label="已拒绝" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="拒绝原因" prop="reason">
          <el-input v-model="addForm.reason" type="textarea" placeholder="请输入拒绝原因（可选）"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit" :loading="addLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="提现审核" :visible.sync="auditDialogVisible" width="500px" :close-on-click-modal="false" custom-class="action-dialog">
      <el-form :model="auditForm" :rules="auditRules" ref="auditForm" label-width="120px">
        <el-form-item label="审核结果" prop="statue">
          <el-radio-group v-model="auditForm.statue">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="拒绝原因" prop="reason" v-if="auditForm.statue === 3">
          <el-input v-model="auditForm.reason" type="textarea" placeholder="请输入拒绝原因"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAuditSubmit" :loading="auditLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑提现申请对话框 -->
    <el-dialog title="编辑提现申请" :visible.sync="editDialogVisible" width="500px" :close-on-click-modal="false" custom-class="action-dialog">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="120px">
        <el-form-item label="用户ID" prop="userId">
          <el-input-number v-model="editForm.userId" :min="1" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="editForm.userType" placeholder="请选择用户类型" style="width: 100%">
            <el-option label="C端用户" :value="1"></el-option>
            <el-option label="业务员" :value="2"></el-option>
            <el-option label="商家" :value="3"></el-option>
            <el-option label="区域代理" :value="4"></el-option>
            <el-option label="总公司" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提现金额(分)" prop="amount">
          <el-input-number v-model="editForm.amount" :min="1" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="拒绝原因" prop="reason">
          <el-input v-model="editForm.reason" type="textarea" placeholder="请输入拒绝原因（可选）"></el-input>
        </el-form-item>
        <el-alert
          v-if="originalStatus === 3"
          title="提示"
          type="warning"
          description="此申请之前被拒绝，修改后将重置为待审核状态，需要重新审核。"
          show-icon
          :closable="false">
        </el-alert>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit" :loading="editLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getWithdrawPage, getWithdrawDetail, checkWithdraw, addWithdraw } from '@/api/aggregation'

export default {
  name: 'WithdrawAudit',
  data() {
    return {
      loading: false,
      searchForm: {
        statue: null,
        startTime: '',
        endTime: ''
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 表格列配置
      tableColumns: [
        { prop: 'id', label: '提现ID', minWidth: 80 },
        { prop: 'userId', label: '用户ID', minWidth: 80 },
        { prop: 'userType', label: '用户类型', minWidth: 100, slot: 'userType' },
        { prop: 'amount', label: '提现金额', minWidth: 120, slot: 'amount' },
        { prop: 'statue', label: '审核状态', minWidth: 100, slot: 'statue' },
        { prop: 'reason', label: '拒绝原因', minWidth: 150, showOverflowTooltip: true },
        { prop: 'createTime', label: '申请时间', minWidth: 180 },
        { prop: 'actions', label: '操作', minWidth: 120, slot: 'actions', fixed: false }
      ],
      // 详情对话框
      detailDialogVisible: false,
      detailData: null,
      // 添加提现申请对话框
      addDialogVisible: false,
      addLoading: false,
      addForm: {
        userId: null,
        userType: null,
        amount: null,
        statue: 1,
        reason: ''
      },
      addRules: {
        userId: [
          { required: true, message: '请输入用户ID', trigger: 'blur' }
        ],
        userType: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入提现金额', trigger: 'blur' }
        ],
        statue: [
          { required: true, message: '请选择审核状态', trigger: 'change' }
        ]
      },
      // 审核对话框
      auditDialogVisible: false,
      auditLoading: false,
      auditForm: {
        id: null,
        statue: null,
        reason: ''
      },
      auditRules: {
        statue: [
          { required: true, message: '请选择审核结果', trigger: 'change' }
        ],
        reason: [
          { required: true, message: '请输入拒绝原因', trigger: 'blur' }
        ]
      },
      // 编辑对话框
      editDialogVisible: false,
      editLoading: false,
      editForm: {
        id: null,
        userId: null,
        userType: null,
        amount: null,
        statue: 1,
        reason: ''
      },
      editRules: {
        userId: [
          { required: true, message: '请输入用户ID', trigger: 'blur' }
        ],
        userType: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入提现金额', trigger: 'blur' }
        ]
      },
      originalStatus: null // 存储原始状态
    }
  },
  computed: {
    // 判断当前用户是否是总公司（userType === 5）
    isHeadquarters() {
      return this.$store.getters.userType === 5
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const params = {
          pageIndex: this.pagination.current,
          pageSize: this.pagination.size
        }

        if (this.searchForm.statue !== null && this.searchForm.statue !== '') {
          params.statue = this.searchForm.statue
        }
        if (this.searchForm.startTime) {
          params.startTime = this.searchForm.startTime
        }
        if (this.searchForm.endTime) {
          params.endTime = this.searchForm.endTime
        }

        Logger.log('发送提现查询API请求，参数:', params)

        // 根据API文档，需要发送完整的参数
        const requestParams = {
          pageIndex: this.pagination.current,
          pageSize: this.pagination.size,
          startTime: this.searchForm.startTime || '',
          endTime: this.searchForm.endTime || '',
          statue: this.searchForm.statue || 0
        }
        Logger.log('完整请求参数:', requestParams)

        const response = await getWithdrawPage(requestParams)
        Logger.log('提现查询API响应:', response)

        if (response.code === 0) {
          this.tableData = response.data.list || []
          this.pagination.total = response.data.total || 0
          Logger.log('加载真实提现数据:', this.tableData)
        } else {
          this.$message.error('API返回失败: ' + (response.msg || '未知错误'))
          this.tableData = []
          this.pagination.total = 0
        }
      } catch (error) {
        Logger.error('加载提现数据失败:', error)
        Logger.error('错误详情:', {
          status: error.response?.status,
          statusText: error.response?.statusText,
          data: error.response?.data,
          config: error.config
        })

        if (error.response && error.response.status === 500) {
          const errorMsg = error.response.data?.message || error.response.data?.error || '服务器内部错误'
          this.$message.error(`服务器错误: ${errorMsg}`)
        } else if (error.response) {
          this.$message.error(`请求失败: ${error.response.status} ${error.response.statusText}`)
        } else {
          this.$message.error('网络错误，请检查网络连接')
        }
        this.tableData = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadData()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        statue: null,
        startTime: '',
        endTime: ''
      }
      this.pagination.current = 1
      this.loadData()
    },

    // 查看详情
    async handleView(row) {
      try {
        Logger.log('查看提现详情，ID:', row.id)
        const response = await getWithdrawDetail(row.id)
        Logger.log('提现详情API响应:', response)

        if (response.code === 0) {
          this.detailData = response.data
          this.detailDialogVisible = true
        } else {
          this.$message.error('获取提现详情失败')
        }
      } catch (error) {
        Logger.error('获取提现详情失败:', error)
        this.$message.error('获取提现详情失败')
      }
    },

    // 通过审核
    handleApprove(row) {
      this.auditForm = {
        id: row.id,
        statue: 2,
        reason: ''
      }
      this.auditDialogVisible = true
    },

    // 拒绝审核
    handleReject(row) {
      this.auditForm = {
        id: row.id,
        statue: 3,
        reason: ''
      }
      this.auditDialogVisible = true
    },

    // 提交审核
    async handleAuditSubmit() {
      try {
        await this.$refs.auditForm.validate()
        this.auditLoading = true

        const params = {
          id: this.auditForm.id,
          statue: this.auditForm.statue
        }
        if (this.auditForm.reason) {
          params.reason = this.auditForm.reason
        }

        Logger.log('提交提现审核，参数:', params)
        const response = await checkWithdraw(params)
        Logger.log('提现审核API响应:', response)

        if (response.code === 0) {
          this.$message.success('审核成功')
          this.auditDialogVisible = false
          this.loadData() // 刷新列表
        } else {
          this.$message.error('审核失败: ' + (response.msg || '未知错误'))
        }
      } catch (error) {
        Logger.error('提现审核失败:', error)
        this.$message.error('审核失败，请重试')
      } finally {
        this.auditLoading = false
      }
    },

    // 显示添加对话框
    showAddDialog() {
      this.addDialogVisible = true
      this.resetAddForm()
    },

    // 重置添加表单
    resetAddForm() {
      this.addForm = {
        userId: null,
        userType: null,
        amount: null,
        statue: 1,
        reason: ''
      }
      if (this.$refs.addForm) {
        this.$refs.addForm.clearValidate()
      }
    },

    // 提交添加
    async handleAddSubmit() {
      try {
        await this.$refs.addForm.validate()
        this.addLoading = true

        // 构建请求参数，确保格式正确
        const params = {
          userId: this.addForm.userId,
          userType: this.addForm.userType,
          amount: this.addForm.amount,
          statue: this.addForm.statue
        }

        // 如果有拒绝原因，添加到参数中
        if (this.addForm.reason && this.addForm.reason.trim()) {
          params.reason = this.addForm.reason.trim()
        }

        Logger.log('=== 添加提现申请参数调试 ===')
        Logger.log('原始表单数据:', this.addForm)
        Logger.log('构建的请求参数:', params)

        const response = await addWithdraw(params)
        Logger.log('添加提现申请API响应:', response)

        if (response.code === 0) {
          this.$message.success('添加成功')
          this.addDialogVisible = false
          this.loadData() // 刷新列表
        } else {
          this.$message.error('添加失败: ' + (response.msg || '未知错误'))
        }
      } catch (error) {
        Logger.error('添加提现申请失败:', error)
        Logger.error('错误详情:', {
          status: error.response?.status,
          statusText: error.response?.statusText,
          data: error.response?.data
        })
        this.$message.error('添加失败，请重试')
      } finally {
        this.addLoading = false
      }
    },

    // 获取状态标签类型
    getStatusTag(status) {
      const statusMap = {
        1: 'warning',  // 待审核
        2: 'success',  // 已通过
        3: 'danger'    // 已拒绝
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '待审核',
        2: '已通过',
        3: '已拒绝'
      }
      return statusMap[status] || '未知'
    },

    // 获取用户类型标签类型
    getUserTypeTag(userType) {
      const typeMap = {
        1: 'info',     // C端用户
        2: 'success',  // 业务员
        3: 'warning',  // 商家
        4: 'primary',  // 区域代理
        5: 'danger'    // 总公司
      }
      return typeMap[userType] || 'info'
    },

    // 获取用户类型文本
    getUserTypeText(userType) {
      const typeMap = {
        1: 'C端用户',
        2: '业务员',
        3: '商家',
        4: '区域代理',
        5: '总公司'
      }
      return typeMap[userType] || '未知'
    },

    // 显示编辑对话框
    handleEdit(row) {
      Logger.log('编辑提现申请:', row)
      this.originalStatus = row.statue // 保存原始状态
      this.editForm = {
        id: row.id,
        userId: row.userId,
        userType: row.userType,
        amount: row.amount,
        statue: row.statue,
        reason: row.reason || ''
      }
      this.editDialogVisible = true
    },

    // 重置编辑表单
    resetEditForm() {
      this.editForm = {
        id: null,
        userId: null,
        userType: null,
        amount: null,
        statue: 1,
        reason: ''
      }
      if (this.$refs.editForm) {
        this.$refs.editForm.clearValidate()
      }
    },

    // 提交编辑
    async handleEditSubmit() {
      try {
        await this.$refs.editForm.validate()
        this.editLoading = true

        // 构建请求参数
        const params = {
          id: this.editForm.id,
          userId: this.editForm.userId,
          userType: this.editForm.userType,
          amount: this.editForm.amount,
          statue: this.editForm.statue
        }

        // 如果有拒绝原因，添加到参数中
        if (this.editForm.reason && this.editForm.reason.trim()) {
          params.reason = this.editForm.reason.trim()
        }

        // 如果原始状态是已拒绝(3)，修改后重置为待审核(1)
        if (this.originalStatus === 3) {
          params.statue = 1
          params.reason = '' // 清空拒绝原因
        }

        Logger.log('=== 编辑提现申请参数调试 ===')
        Logger.log('原始状态:', this.originalStatus)
        Logger.log('编辑表单数据:', this.editForm)
        Logger.log('构建的请求参数:', params)

        const response = await addWithdraw(params) // 使用添加接口进行编辑
        Logger.log('编辑提现申请API响应:', response)

        if (response.code === 0) {
          const message = this.originalStatus === 3 ? '重新提交成功，状态已重置为待审核' : '编辑成功'
          this.$message.success(message)
          this.editDialogVisible = false
          this.loadData() // 刷新列表
        } else {
          this.$message.error('编辑失败: ' + (response.msg || '未知错误'))
        }
      } catch (error) {
        Logger.error('编辑提现申请失败:', error)
        Logger.error('错误详情:', {
          status: error.response?.status,
          statusText: error.response?.statusText,
          data: error.response?.data
        })
        this.$message.error('编辑失败，请重试')
      } finally {
        this.editLoading = false
      }
    },

  }
}
</script>

<style scoped>
.withdraw-audit {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

/* 详情对话框样式 */
.detail-content {
  padding: 20px 0;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: bold;
  min-width: 120px;
  color: #606266;
}

.detail-item span {
  flex: 1;
  color: #303133;
}

/* 对话框底部样式已移至公共样式 dialog.scss */

/* 表格样式优化 */
.el-table {
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background: #f5f7fa;
  color: #606266;
  font-weight: 600;
}


/* 状态标签样式优化 */
.el-tag {
  border-radius: 12px;
  font-weight: 500;
  padding: 4px 12px;
}

/* 页面标题样式 */
.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

/* 头部操作区域 */
.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 添加按钮样式 */
.add-btn {
  position: relative;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  font-size: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
}

.add-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.6);
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.add-btn:hover::before {
  left: 100%;
}

.add-btn:active {
  transform: translateY(0);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.add-btn .btn-text {
  position: relative;
  z-index: 1;
}

.add-btn .el-icon-plus {
  margin-right: 8px;
  font-size: 16px;
}

/* 卡片头部样式 */
.el-card__header {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #dee2e6;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;
}

.el-card__header .clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-card__header .page-title {
  color: #2c3e50;
  font-size: 22px;
  font-weight: 700;
  letter-spacing: 0.5px;
}
</style>
